﻿using Jay.Sc2.Bof.Lib.State;
using Jay.Sc2.Bof.Lib.Tools;

namespace Jay.Sc2.Bof.Lib.Action.Terran
{
	public class ActionProduceSCV : ActionProduceTerran
	{
		public static ActionProduceSCV Instance = new ActionProduceSCV();

		private ActionProduceSCV() : base(17, 50, 0, 1) { }

		public override int AvailableProducer(IBuildOrder bo)
		{
			TerranState state = bo.State as TerranState;
			return
				(state.CommandCenter.Count - state.CommandCenter.Production) +
				(state.OrbitalCommand.Count - state.OrbitalCommand.Production) +
				(state.PlanetaryFortress.Count - state.PlanetaryFortress.Production);
		}

		public override bool CanExecute(IBuildOrder bo)
		{
			return bo.State.Workers < IncomeUtil.GetSaturationWorkerCount(bo.State.MineralPatches, bo.State.GasBuilding.Count) && base.CanExecute(bo);
		}

		public override bool HaveTechnology(IBuildOrder bo) { return true; }

		public void OnProductionFinished(IBuildOrder bo)
		{
			TerranState state = bo.State as TerranState;
			state.SCV++;
			state.WorkersOnMinerals++;
		}

		public override void Execute(IBuildOrder bo)
		{
			TerranState state = bo.State as TerranState;
			int fromPlanetary = (state.PlanetaryFortress.Count - state.PlanetaryFortress.Production);
			int fromOrbital = (state.OrbitalCommand.Count - state.OrbitalCommand.Production);
			int fromCommand = (state.CommandCenter.Count - state.CommandCenter.Production);
			if (fromPlanetary > 0)
			{
				base.Execute(bo);
				state.PlanetaryFortress.Production++;
				bo.AddAction(state.Time + BuildTime, new ActionGeneric("ActionSpawnSCV", (ActionGeneric.ActionExecuteDelegate)delegate(IBuildOrder ibo)
				{
					TerranState ibostate = ibo.State as TerranState;
					ibostate.PlanetaryFortress.Production--;
					OnProductionFinished(ibo);
				}));
			}
			else if (fromOrbital > 0)
			{
				base.Execute(bo);
				state.OrbitalCommand.Production++;
				bo.AddAction(state.Time + BuildTime, new ActionGeneric("ActionSpawnSCV", (ActionGeneric.ActionExecuteDelegate)delegate(IBuildOrder ibo)
				{
					TerranState ibostate = ibo.State as TerranState;
					ibostate.OrbitalCommand.Production--;
					OnProductionFinished(ibo);
				}));
			}
			else if (fromCommand > 0)
			{
				base.Execute(bo);
				state.CommandCenter.Production++;
				bo.AddAction(state.Time + BuildTime, new ActionGeneric("ActionSpawnSCV", (ActionGeneric.ActionExecuteDelegate)delegate(IBuildOrder ibo)
				{
					TerranState ibostate = ibo.State as TerranState;
					ibostate.CommandCenter.Production--;
					OnProductionFinished(ibo);
				}));
			}
			else throw new InvalidActionException();
		}
	}
}
